import { useEffect, useRef } from 'react';
// import data from '../data.json';
import './index.less';
const observer = new IntersectionObserver(
  (entries) => {
    console.log('entries', entries);
    //entries: 是监听所有IntersectionObserverEntry的集合
    entries.forEach(({ isIntersecting, target }) => {
      // isIntersecting是一个Boolean值，判断目标元素当前是否可见
      if (isIntersecting) {
        // 进入可视区域替换真实图片地址(定时器延迟加载好观察效果)
        setTimeout(() => {
          target.src = target.getAttribute('url');
        }, 2000);
        // 图片加载后即停止监听该元素
        observer.unobserve(target);
      }
    });
  },
  {
    root: document.querySelector('#masonry3'),
  },
);
/* imgs是二维数组 */
function lazyLoad(arr) {
  console.log('懒加载被触发了！');
  for (let i = 0; i < arr.length; i++) {
    const imgs = arr[i];
    for (let j = 0; j < arr[i].length; j++) {
      /* 遍历监听所有img */
      observer.observe(imgs[j]);
    }
  }
}

const gridCols = () => {
  let data = [];
  for (let i = 0; i < 100; i++) {
    let num = parseInt(Math.random() * (400 - 100 + 1) + 100);
    let num1 = parseInt(Math.random() * (400 - 100 + 1) + 100);
    let num2 = parseInt(Math.random() * (50 - 1 + 1) + 1);
    let newnum = `https://picsum.photos/${num}/${num1}?random=${num2}`;
    data.push(newnum);
  }
  const newData = data.map((url, id) => {
    return {
      id,
      url,
      text: id > 30 ? '阿发发生公司大概啊啊啊啊啊啊啊啊啊啊啊' : 'test111111',
    };
  });
  console.log('newData', newData);
  useEffect(() => {
    const nodeList1 = document
      .querySelector('#masonry3')
      .querySelector('.colmun1')
      .querySelectorAll('.item');
    const nodeList2 = document
      .querySelector('#masonry3')
      .querySelector('.colmun2')
      .querySelectorAll('.item');
    const nodeList3 = document
      .querySelector('#masonry3')
      .querySelector('.colmun3')
      .querySelectorAll('.item');
    const nodeArr = [nodeList1, nodeList2, nodeList3];
    // 进入页面时执行一次加载；
    lazyLoad(nodeArr);
    // 监听滚动事件，进行图片懒加载；
  }, []);
  return (
    <div className="masonry3" id="masonry3">
      <div className="colmun1">
        {newData.slice(0, 33).map((item) => {
          return <img className="item" url={item.url} key={item.id}></img>;
        })}
      </div>
      <div className="colmun2">
        {newData.slice(33, 66).map((item) => {
          return <img className="item" url={item.url} key={item.id}></img>;
        })}
      </div>
      <div className="colmun3">
        {newData.slice(66, 101).map((item) => {
          return <img className="item" url={item.url} key={item.id}></img>;
        })}
      </div>
    </div>
  );
};
export default gridCols;
